package visitors

import (
	"context"
	uuid "github.com/satori/go.uuid"
	"log"
	"net/http"
	"time"
	"wave-service/server/app/common/jwtx"
	"wave-service/server/app/common/response"
	"wave-service/server/app/common/utils"
	"wave-service/server/app/models"

	"wave-service/server/app/internal/svc"
	"wave-service/server/app/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type VisitorLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewVisitorLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VisitorLoginLogic {
	return &VisitorLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *VisitorLoginLogic) VisitorLogin(req *types.LoginRequest, r *http.Request) (resp *types.LoginResponse, err error) {
	ip := utils.RemoteIp(r)
	// 判断ip是否已经注册
	log.Println("ip=", ip)
	user, _err := l.svcCtx.VisitorsModel.FindOneByClientIp(l.ctx, ip)
	var uid int64
	if _err == models.ErrNotFound {
		province, city := utils.IpPlace(ip, l.svcCtx.Config.IpPlace.AppKey, l.svcCtx.Config.IpPlace.Sign)
		log.Println("province=", province, " city=", city)
		newUser := models.CusVisitors{
			Uuid:      uuid.NewV4().String(),
			Nickname:  utils.RandomString(10),
			Avatar:    "",
			ClientIp:  ip,
			Province:  province,
			City:      city,
			Status:    1,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}

		res, err := l.svcCtx.VisitorsModel.Insert(l.ctx, &newUser)
		if err != nil {
			logx.Errorf("ip=%v 注册失败 %v", ip, err.Error())
			return nil, response.Error(500, "注册失败")
		}

		newUser.Id, err = res.LastInsertId()
		if err != nil {
			logx.Errorf("ip=%v 获取用户id失败 %v", ip, err.Error())
			return nil, response.Error(500, "注册失败2")
		}
		uid = newUser.Id

		// 用户详细信息
		agent := r.Header.Get("User-Agent")
		refer := r.Header.Get("Referer")
		host := r.Header.Get("Origin")
		log.Println("浏览器=", agent, " 来源=", refer, " HOST=", host)
		detail := models.CusVisitorDetails{
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			VisitorId: uid,
			Browser:   agent,
			Refer:     refer,
			Host:      host,
			Visits:    0,
		}
		_, err = l.svcCtx.VisitorDetailsModel.Insert(l.ctx, &detail)
		if err != nil {
			logx.Errorf("ip=%v 用户详细信息添加失败 %v", ip, err.Error())
			return nil, response.Error(500, "用户详细信息添加失败")
		}

	} else if _err != nil {
		logx.Errorf("ip=%v 登录失败 %v", ip, _err.Error())
		return nil, response.Error(500, "登录失败")
	} else {
		uid = user.Id
	}
	log.Println("uid=", uid)

	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire

	accessToken, err := jwtx.GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, uid)
	if err != nil {
		return nil, response.Error(500, err.Error())
	}

	return &types.LoginResponse{
		AccessToken:  accessToken,
		AccessExpire: now + accessExpire,
	}, nil
}
